package com.edu.hre.db.sql.admin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HrePayGrade;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.PayGradeForm;
import com.edu.hre.struts.form.admin.PayGradeListForm;

public class PayGradeDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "payGradeDAOService";
	private BaseService baseService  = null;
	 
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	} 

	public ArrayList<PayGradeForm> getPayGradeListInfo(int limit, int offset){

		ArrayList<PayGradeForm> listResult = new ArrayList<PayGradeForm>();
		String sql = "SELECT pay.id AS col1," +
					" pay.name AS col2, " +
					" pay.min_salary AS col3, " +
					" pay.max_salary AS col4, " +
					" typ.currency_id AS col5 " +
					
					" FROM hre_pay_grade AS pay," +
					" hre_currency_type AS typ" +
					
					" WHERE pay.currency_id = typ.currency_id" +
					" ORDER BY pay.date_created DESC";
		
		List <Object[]> listObject = baseService.listArrayObject(sql, limit, offset);
		for(int i = 0; listObject != null && i < listObject.size(); i++){
			
			try {

				Object[] objs = listObject.get(i);
				PayGradeForm payGradeForm = new PayGradeForm();

				payGradeForm.setId(CommonUtils.normalizeObjectToString(objs[1], "0"));
				payGradeForm.setPayGrade(CommonUtils.normalizeObjectToString(objs[2], ""));
				payGradeForm.setMinSalary(Double.parseDouble(CommonUtils.normalizeObjectToString(objs[3], "0")));
				payGradeForm.setMaxSalary(Double.parseDouble(CommonUtils.normalizeObjectToString(objs[4], "0")));
				payGradeForm.setMinSalaryStr(String.format("%,10.2f", payGradeForm.getMinSalary()));
				payGradeForm.setMaxSalaryStr(String.format("%,10.2f", payGradeForm.getMaxSalary()));
				payGradeForm.setCurrency(CommonUtils.normalizeObjectToString(objs[5], ""));

				listResult.add(payGradeForm);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}

		return listResult;
	}
	
	public int countPayGrades(){

		int count = baseService.countByColumns(null, null, null, "id", HrePayGrade.class);
		return count < 0 ? 0 : count;
	}

	public void deletePayGrades(PayGradeListForm form){

		ArrayList<PayGradeForm> info = (ArrayList<PayGradeForm>) form.getAllGrades();
		
		for (int i = 0; i < info.size(); i++) {
			
			try {

				PayGradeForm grade = info.get(i);
				if (grade.isSelected()) {
					baseService.deleteFirstPojo("id", Compare.EQUAL, Integer.parseInt(grade.getId()), null, null, 0, HrePayGrade.class);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
